<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CutdownFollow;
use app\common\logic\CutdownLogic;
use app\common\model\Goods;
use think\Db;

/**
 * 砍价接口
 */
class Cutdown extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Cutdown();

    }

    public function index()
    {
        $this->limitFields = 'id,goods_id,price,image,description,min_price';
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();


        $total = $this->model
            ->where($where)
            ->where(function ($query) use ($where) {
                $query->where('status', 1);
                $query->where('is_end', 0);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->field($field)
            ->where($where)
            ->where(function ($query) use ($where) {
                $query->where('status', 1);
                $query->where('is_end', 0);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $result = array("total" => $total, "rows" => $list);

        $this->success('', $result);
    }


    /**
     * 查看
     */


    /**
     * 用户发起砍价
     * $ids 砍价活动id
     */
    public function cut($ids)
    {
        $cutdown = Db::name('cutdown')->find($ids);
        if($cutdown['is_end'] == 1){
            $this->error('砍价活动已结束!');
        }
        if (!$cutdown) {
            $this->error('记录未找到');
        }

        //有砍价正在进行，等完成才能发起新的
        $cutdownFollowLogic = new \app\common\logic\CutdownFollowLogic();
        $isHasCut = $cutdownFollowLogic->canCutNew($ids, $this->auth->id);
//dump($isHasCut);exit;
        if ($isHasCut['code'] == 0) {
            $this->error($isHasCut['msg'], $isHasCut['data']);
        }

        //首次发起砍价，砍掉的金额为中间金额
//        $first_cut_price = floor(($cutdown['max_cut_price'] * 100 - $cutdown['min_cut_price'] * 100) / 2) / 100;
        $first_cut_price = rand($cutdown['min_cut_price'] * 100, $cutdown['max_cut_price'] * 100) / 100;
        $deal_price = ($cutdown['price'] * 100 - $first_cut_price * 100) / 100;

        $data = [
            'cutdown_id' => $ids,
            'goods_id' => $cutdown['goods_id'],
            'item_id' => $cutdown['item_id'],
            'createtime' => time(),
            'deal_price' => $deal_price,
            'user_id' => $this->auth->id
        ];
        $id = Db::name('cutdown_follow')->insertGetId($data);

        if ($id) {
            $res = $this->model->addCutdownList($this->auth->id, $id, 1, $first_cut_price);

            if ($res['code'] == 1) {


                $this->success('发起砍价成功', $res['data']);
            } else {
                $this->error($res['msg']);
            }
        } else {
            $this->error('发起砍价失败');
        }
    }

    /**
     * 好友帮砍价
     */
    public function helpcut()
    {


        $cutdown_follow_id = $this->request->request('cutdown_follow_id');
        $cutdownFollow = CutdownFollow::get($cutdown_follow_id);
        $goods = Goods::get($cutdownFollow['goods_id']);
        $cutdownLogic = new CutdownLogic($goods);
        $cutdown = $this->model->get($cutdownFollow['cutdown_id']);


        //是否在砍价有效期内
        $isInTime = $cutdownLogic->isInTime($cutdown_follow_id);
        if (!$isInTime) {
            $this->error('砍价已结束');

        }

        $isCut = $cutdownLogic->isFirstCut($cutdown_follow_id, $this->auth->id);
        //每天限制好友可帮砍一次
        if ($isCut['code'] == 0) {
            $this->error('每天只能帮好友砍价一次，明天再来哦', $isCut['data']);
        }

        if ($cutdownFollow['status'] == 1) {
            $data = $cutdownLogic->getKanJiaYeMian($cutdown_follow_id);
            $this->error('砍价已完成', $data);
        }

        $return = $this->model->addCutdownList($this->auth->id, $cutdown_follow_id);


        if ($return['code'] == 1) {

            $deal_price = ($cutdown['price'] * 100 - $return['data']['yikan'] * 100) / 100;
            $cut_count = intval($return['data']['cut_count']) + 1;

            Db::name('cutdown_follow')->where(['id' => $cutdown_follow_id])->update(['deal_price' => $deal_price, 'cut_count' => $cut_count]);

            $this->success('砍价成功', $return['data']);
        } else {

            //砍价活动信息


            $this->error($return['msg'], $return['data']);
        }
    }


    /**
     * 详情
     */
    public function detail($goods_id = NULL)
    {
        \app\common\model\Goods::addzuji($goods_id,$this->auth->id);
        $row = \app\common\model\Goods::get($goods_id);
        if (!$row)
            $this->error(__('No Results were found'));

        $goodsAttrData = Db::name('goods_attr')->alias('ga')
            ->join('attr a', 'ga.attr_id = a.id', 'LEFT')
            ->where(['goods_id' => $goods_id])
            ->field('a.name')
            ->find();
        $row['attrName'] = $goodsAttrData['name'];

        $goodsAttrM = model('common/goodsAttr');
        $goodsAttr = $goodsAttrM->field('id,attr_value')->where(['goods_id' => $goods_id])->select();

        $row['goodsAttr'] = $goodsAttr;
        $row['type'] = \app\common\model\Goods::getType();


        if ($row['prom_type'] == 2) {
            $row['type'] = [
                ['id' => '0', 'name' => '自己买'],
                ['id' => '1', 'name' => '送一人']
            ];
        }

        $goodsPromFactory = new \app\common\logic\GoodsPromFactory();
        if (!empty($row['prom_id']) && $goodsPromFactory->checkPromType($row['prom_type'])) {
            $goodsPromLogic = $goodsPromFactory->makeModule($row);//这里会自动更新商品活动状态，所以商品需要重新查询
            $row = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询

            $ActivityGoodsInfo = $goodsPromLogic->getActivityGoodsInfo();

            if (isset($ActivityGoodsInfo['item_id']) && $ActivityGoodsInfo['item_id']) {
                $ActivityGoodsInfo['goodsAttr'] = $goodsAttrM->field(['id,attr_value'])->where(['id' => $ActivityGoodsInfo['item_id']])->select();
            }

            $row = $ActivityGoodsInfo;
        }

        $this->success('', $row);
    }


}